#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/10/22 22:53
# @Author  : when
# @File    : base_model.py
# @Description :

from functools import cmp_to_key
from sqlalchemy import Column, String, TIMESTAMP
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class BaseModel:
    # 公共字段
    update_time = Column(TIMESTAMP)
    created_time = Column(TIMESTAMP)
    is_removed = Column(String(10), default="f")

    def to_string(self):
        attr_list = [attr for attr in dir(self) if not attr.startswith("_")]
        # 按照len(attr)从小到大排序
        attr_list.sort(key=cmp_to_key(lambda x, y: len(x) - len(y)))
        attr_list = [f"{attr}={str(getattr(self, attr))}" for attr in attr_list]
        # 过滤指定元素
        filter_attr = ["BaseModel", "metadata", "sqlalchemy"]
        # 倒序遍历删除list
        for i in range(len(attr_list) - 1, -1, -1):
            v = attr_list[i]
            is_filter = False
            for k in filter_attr:
                is_filter = True if k in v else is_filter
            if is_filter:
                attr_list.remove(v)
        class_name = [str(self.__class__)[0:-2], "({})", str(self.__class__)[-2:]]
        class_name = "".join(class_name)
        return class_name.format({', '.join(attr_list)})
